package com.rran.study.chat.server.core.model;

import com.rran.study.chat.server.core.annotations.AcceptMapping;
import com.rran.study.chat.server.dto.request.ChatMessage;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import org.omg.SendingContext.RunTime;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author yy
 * @Type Accept.java
 * @Desc
 * @date 2020/8/9 17:49
 */
@Data
public class AcceptBean {

    private Object accept;
    private Method method;
    private Pattern pattern;
    private Map<String, Integer> paramIndexMapping;

    public AcceptBean(Object accept, Method method, Pattern pattern) {
        this.accept = accept;
        this.method = method;
        this.pattern = pattern;
        this.paramIndexMapping = new HashMap<>();
        putParamIndexMapping(method);
    }

    private void putParamIndexMapping(Method method) {
        Class<?>[] paramTypes = method.getParameterTypes();
        if (2 < paramTypes.length) {
            throw new RuntimeException("Accept method params length must less than or equal to 2");
        }
        for (int i = 0; i < paramTypes.length; i++) {
            Class<?> type = paramTypes[i];
            if (ChatMessage.class.isAssignableFrom(type) || type == ChannelHandlerContext.class) {
                paramIndexMapping.put(type.getName(), i);
            } else {
                throw new RuntimeException("Accept method params instance is must instanceof ChannelHandlerContext or ChatMessage");
            }
        }
    }

}
